package com.manli.api.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.manli.api.base.config.JwtAuthTokenTimeConfig;
import com.manli.api.dto.UserLinkUnionid;
import com.manli.api.util.JwtUtils;
import com.manli.common.utils.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.manli.api.base.exception.MyException;
import com.manli.api.dto.User;
import com.manli.api.pojo.SessionInfo;
import com.manli.api.pojo.UserPermission;


@Service
@Transactional
public class LoginService {
	
	@Autowired
	UserPermissionService userPermissionService;

	@Autowired
	UserLinkUnionidService userLinkUnionidService;

	@Autowired
	RedisTemplate redisTemplate;
	
	@SuppressWarnings("null")
	public SessionInfo getSessionInfoByNameAndPasswd(User account,HttpServletRequest request) throws Exception{
		if(StringUtils.isEmpty(account.getUsername()) || StringUtils.isEmpty(account.getPassword())){
			throw new MyException(-1,"用户名或密码为空");
		}

		SessionInfo sessionInfo = null;
//		User user = userPermissionService.getUserByNameAndPasswd(account.getUsername(),account.getPassword(),account.getLoginBranchPartnerName());

		User user = userPermissionService.getUserAndPasswd(account.getUsername(),account.getPassword());

		if(user !=null ) {
			sessionInfo = this.userInfoCovertToSessionInfo(user);
			UserLinkUnionid userLinkUnionid = userLinkUnionidService.getByUserId(user.getUserId(),1);
			if(userLinkUnionid != null){
				sessionInfo.setUnionid(userLinkUnionid.getUnionid());
			}
		}
		return sessionInfo;
	}

	public SessionInfo userInfoCovertToSessionInfo(User user){
		SessionInfo sessionInfo = new SessionInfo();
		if(user !=null ) {
			//获取用户权限
			List<UserPermission> userPermissions = userPermissionService.getUserPermission(user.getUserId(),user.getBranchId());
			sessionInfo.setName(user.getUsername());
			sessionInfo.setUserId(user.getUserId());
			sessionInfo.setUserPermissions(userPermissions);
			sessionInfo.setBranchId(user.getBranchId());
			sessionInfo.setBranchName(user.getBranchName());
			sessionInfo.setPartnerId(user.getPartnerId());
			sessionInfo.setPartnerName(user.getPartnerName());
			sessionInfo.setUserPhone(user.getUserPhone());
			if(user !=null ) {
				UserLinkUnionid userLinkUnionid = userLinkUnionidService.getByUserId(user.getUserId(),1);
				if(userLinkUnionid != null){
					sessionInfo.setUnionid(userLinkUnionid.getUnionid());
				}
			}
		}
		return sessionInfo;
	}

	public JSONObject getAuthToken(SessionInfo sessionInfo) {
		JSON jsons = (JSON)JSON.toJSON(sessionInfo);
		Map<String,Object> claims = new HashMap<String, Object>();
		claims.put("userId", sessionInfo.getUserId());
		claims.put("userName", sessionInfo.getName());
		String auth_token = JwtUtils.createJWT(claims, JwtAuthTokenTimeConfig.JwtAuthTokenExpireTime);
		/**
		 * 增加refresh_token用于token过期续期
		 */
		claims.put("randomNum", RandomUtils.getRandNumByLength(10));
		String refresh_token = JwtUtils.createJWT(claims, JwtAuthTokenTimeConfig.JwtRefreshTokenExpireTime);
		//sessionInfo存入redis
		redisTemplate.opsForValue().set("auth_token:"+sessionInfo.getUserId()+":"+sessionInfo.getName(), sessionInfo,JwtAuthTokenTimeConfig.JwtAuthTokenRedisExpireTime, TimeUnit.SECONDS);
		JSONObject object = new JSONObject();
		object.put("auth_token", auth_token);
		object.put("refresh_token", refresh_token);
		object.put("menus",userPermissionService.getUserPermissionVue(sessionInfo.getUserId(),sessionInfo.getBranchId()));
		object.put("sessionInfo",sessionInfo);
		return object;
	}
}
